package com.opac.readerhome.plugin;

import java.util.Collections;
import java.util.List;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

public class OpenOtherApp extends CordovaPlugin{
	@Override
	public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
		if(action.equals("qq") ){
			return openQQ(callbackContext);
		}
		return false;
	}

	private boolean openQQ(CallbackContext callbackContext) {
		Context mContext=cordova.getActivity();   
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		 PackageManager mPackageManager = mContext.getPackageManager();  
		 List<ResolveInfo> mAllApps = mPackageManager.queryIntentActivities(mainIntent, 0);  
		 //按报名排序  
		 Collections.sort(mAllApps, new ResolveInfo.DisplayNameComparator(mPackageManager));  
		 
		 for(ResolveInfo res : mAllApps){  
		        //该应用的包名和主Activity  
		        String pkg = res.activityInfo.packageName;  
		        String cls = res.activityInfo.name;  
		        // 打开QQ  
		        if(pkg.contains("qq")){  
		            ComponentName componet = new ComponentName(pkg, cls);  
		            Intent intent = new Intent();  
		            intent.setComponent(componet);  
		            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
		            this.cordova.getActivity().startActivity(intent);  
		            return true;
		        }
		 }  
		 callbackContext.error("您的手机没有安装QQ");
		 return false;
	}
}
